package utils

import (
	"MoSkeleton/framework/core/config/properties_gin"
	"MoSkeleton/framework/core/dto/request"
	"github.com/golang/groupcache/singleflight"
	"time"

	jwt "github.com/golang-jwt/jwt/v5"
)

var syncGroup = &singleflight.Group{}

type JWT struct {
	SigningKey []byte
}

func NewJWT(jwtBaseProperty *properties_gin.JwtProperty) *JWT {
	return &JWT{
		[]byte(jwtBaseProperty.SigningKey),
	}
}

func (j *JWT) CreateClaims(baseClaims request.BaseClaims, jwtBaseProperty *properties_gin.JwtProperty) request.MoClaims {
	bf, _ := ParseDuration(jwtBaseProperty.BufferTime)
	ep, _ := ParseDuration(jwtBaseProperty.ExpiresTime)
	claims := request.MoClaims{
		BaseClaims: baseClaims,
		BufferTime: int64(bf / time.Second), // 缓冲时间1天 缓冲时间内会获得新的token刷新令牌 此时一个用户会存在两个有效令牌 但是前端只留一个 另一个会丢失
		RegisteredClaims: jwt.RegisteredClaims{
			Audience:  jwt.ClaimStrings{"MO"},                    // 受众
			NotBefore: jwt.NewNumericDate(time.Now().Add(-1000)), // 签名生效时间
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(ep)),    // 过期时间 7天  配置文件
			Issuer:    jwtBaseProperty.Issuer,                    // 签名的发行者
		},
	}
	return claims
}

// 创建一个token
func (j *JWT) CreateToken(claims request.MoClaims) (string, error) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(j.SigningKey)
}

// CreateTokenByOldToken 旧token 换新token 使用归并回源避免并发问题
func (j *JWT) CreateTokenByOldToken(oldToken string, claims request.MoClaims) (string, error) {
	v, err := syncGroup.Do("JWT:"+oldToken, func() (interface{}, error) {
		return j.CreateToken(claims)
	})
	return v.(string), err
}

// 解析 token
func (j *JWT) ParseToken(tokenString string) (*request.MoClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &request.MoClaims{}, func(token *jwt.Token) (i interface{}, e error) {
		return j.SigningKey, nil
	})
	if err != nil {
		return nil, err
		//if ve.Errors&jwt.ValidationErrorMalformed != 0 {
		//
		//} else if ve.Errors&jwt.ValidationErrorExpired != 0 {
		//	// Token is expired
		//	return nil, TokenExpired
		//} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {
		//	return nil, TokenNotValidYet
		//} else {
		//	return nil, TokenInvalid
		//}
	}
	if token != nil {
		if claims, ok := token.Claims.(*request.MoClaims); ok && token.Valid {
			return claims, nil
		}
		return nil, jwt.ErrTokenInvalidId

	} else {
		return nil, jwt.ErrTokenInvalidId
	}
}
